package com.acwing.partition9;

import java.io.*;

/**
 * @author `RKC`
 * @date 2021/12/6 11:24
 */
public class AC887求组合数III {

    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
        String[] s = reader.readLine().split(" ");
        int n = Integer.parseInt(s[0]);
        while (n-- > 0) {
            s = reader.readLine().split(" ");
            long a = Long.parseLong(s[0]), b = Long.parseLong(s[1]), p = Long.parseLong(s[2]);
            writer.write(lucas(a, b, p) + "\n");
        }
        writer.flush();
    }

    private static long lucas(long a, long b, long p) {
        if (a < p && b < p) return c(a, b, p);
        //a % p后肯定是小于p的,所以可以直接调用函数进行计算,但a/p后不一定小于 所以用lucas继续递归
        return c(a % p, b % p, p) * lucas(a / p, b / p, p) % p;
    }

    private static long c(long a, long b, long p) {
        if (b > a) return 0;
        long res = 1;
        for (long i = 1, j = a; i <= b; i++, j--) {
            // a!/(b!(a-b)!) = (a-b+1)*...*a / b! 分子有b项
            res = res * j % p * quickPow(i, p - 2, p) % p;
        }
        return res;
    }

    private static long quickPow(long a, long k, long p) {
        long res = 1;
        while (k != 0) {
            if ((k & 1) == 1) res = res * a % p;
            k >>= 1;
            a = a * a % p;
        }
        return res;
    }
}
